package com.urfresh.sp.user.schedule.service;

import com.alibaba.fastjson.JSON;
import com.mongodb.MongoClient;
import com.mongodb.client.model.Filters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 控制活动的启动
 * 把充值，发券，推动，短信等业务封装成单独的unit，再通过顺序依次调用
 * 注意，这个类的执行是从active_main表作为入口
 * Created by urfresh.mark on 2017/2/7.
 */
@Service
@EnableScheduling
@EnableAsync
public class ActiveSchedule {

    protected Logger logger = LoggerFactory.getLogger(ActiveSchedule.class);

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    MongoClient mongoClient;

    @Autowired
    JedisPool pool;

    String LOG_1 = "%s尚未到达活动开始时间,开始时间:%s,当前时间:%s";

    //读取尚未开始的服务
//    @Scheduled(cron = "0 0 2 * * ?")
    public void start() {
        logger.info("开始防黄牛用户的执行定时任务");

        int start = 0;
        int count = 0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //清空所有记录
        mongoClient.getDatabase("bind_user").getCollection("bind_user").deleteMany(Filters.lt("create_time", dateFormat.format(new Date())));

        while (true) {
            List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT * FROM `dw_bind_user` limit " + start + ", 10000");

            List<Map<String, Object>> l = list.parallelStream().map(m -> {
                m.put("create_time", dateFormat.format(new Date()));
                return m;
            }).collect(Collectors.toList());

            mongoTemplate.insert(l, "bind_user");
            logger.info("已保存：" + (list.size() + start));

            start += 10000;
            if (list.size() < 10000) {
                logger.info("已完成");
                break;
            }
        }
    }

    public void test1() {
        int start = 0;
        int count = 0;
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        while (true) {
            List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT user_name, traffic_bind_user_num, traffic_bind_device_num, traffic_bind_user, traffic_bind_device FROM `dw_bind_user` limit " + start + ", 10000");
            try (Jedis jedis = pool.getResource();
                 Pipeline pipeline = jedis.pipelined()) {

                for(Map m : list) {
                    if(m.get("traffic_bind_user_num")==null || m.get("traffic_bind_user")==null || m.get("traffic_bind_device_num")==null || m.get("traffic_bind_device")==null)
                        continue;

                    String traffic_bind_user = format(String.valueOf(m.get("traffic_bind_user")));
                    String traffic_bind_device = format(String.valueOf(m.get("traffic_bind_device")));
                    String traffic_bind_user_num = String.valueOf(m.get("traffic_bind_user_num"));
                    String traffic_bind_device_num = String.valueOf(m.get("traffic_bind_device_num"));

                    String[] traffic_bind_user_list = traffic_bind_user.split(",");
                    String[] traffic_bind_device_list = traffic_bind_device.split(",");

                    //用户名称维度
                    HashMap<String, String> userNameMap = new HashMap<String, String>();
                    userNameMap.put("traffic_bind_user_num", traffic_bind_user_num);
                    userNameMap.put("traffic_bind_device_num", traffic_bind_device_num);
                    userNameMap.put("traffic_bind_user", JSON.toJSONString(traffic_bind_user_list));
                    userNameMap.put("traffic_bind_device", JSON.toJSONString(traffic_bind_device_list));

                    for(String d : traffic_bind_device_list) {
                        //设备维度
                        HashMap<String, String> deviceMap = new HashMap<String, String>();
                        deviceMap.put("traffic_bind_device", d);
                        deviceMap.put("traffic_bind_device_num", traffic_bind_device_num);
                        deviceMap.put("traffic_bind_user", JSON.toJSONString(traffic_bind_user_list));
                        deviceMap.put("traffic_bind_user_num", traffic_bind_user_num);
                        pipeline.hmset("device:" + d, deviceMap);
                    }

                    pipeline.hmset("userName:" + m.get("user_name").toString(), userNameMap);

                }
                pipeline.sync();
            } catch (IOException e) {
                e.printStackTrace();
            }

            logger.info("已保存：" + (list.size() + start));

            start += 10000;
            if (list.size() < 10000) {
                logger.info("已完成");
                break;
            }
        }
    }

    private static String format(String source) {
        String value = source;
        value = value.substring(1, value.length() - 1);
        if (value.endsWith(","))
            value = value.substring(0, value.length() - 1);
        return value.replaceAll(" ","");
    }

    public static void main(String[] args) {
        String s = "(E9ED3D15-2D9B-454B-A1CF-232F69028DBF, c62eb00f73757ee4)";
        s = format(s).replaceAll(" ","");
        System.out.println(s);
        String ddd = JSON.toJSONString(Arrays.asList(s.split(",")));
        System.out.println(ddd);
    }

}
